<template>
  <van-button
    v-if="isFollowed"
    :loading="loading"
    @click="onFollow"
    class="follow-btn"
    round
    size="small"
    >已关注</van-button
  >
  <van-button
    v-else
    @click="onFollow"
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="loading"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from "@/api/user.js";
export default {
  name: "FollowUser",
  // 自定义 v-model 的数据名称
  model: {
    prop: "isFollowed", // 默认是 isFollowed
    event: "update-is_followed", // 默认是 input
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true,
    },
    userId: {
      type: [Number, String, Object],
      required: true,
    },
  },
  components: {},
  data() {
    return {
      loading: false, // loading 状态显示与否
    };
  },
  methods: {
    // 关注和取消关注
    async onFollow() {
      this.followLoading = true;
      try {
        if (this.isFollowed) {
          // 已关注，取消关注
          await deleteFollow(this.userId);
        } else {
          await addFollow(this.userId);
        }
        // 把!this.isFollowed这个值传给父组件
        this.$emit("update-is_followed", !this.isFollowed);
      } catch (error) {
        let message = "操作失败，请重试";
        if (error.response && error.response.status === 400) {
          message = "你不能关注你自己！";
        }
        this.$toast(message);
      }
      this.followLoading = false;
    },
  },
};
</script>

<style lang="less" scoped></style>
